<template>
  <view :class="theme">
    <view class="bg-4 b-rounded-16 p-30 m-30">
      <view class="items-center">
        <!-- <text v-if="goodsInfo.description" class="mt-30 mb-30 text-32 flex-1">{{ goodsInfo.description }}</text> -->
        <view v-if="goodsInfo.description" class="flex-1 justify-center">
          <text class="mt-10 text-28 multi-ellipsis">{{ goodsInfo.description }}</text>
        </view>
        <uv-image width="234" height="156" src="/static/img/img-pay.png" />

        <text class="mt-60 text-30">支付金额</text>
        <input v-model="goodsInfo.amount" :disabled="goodsInfo.order_type !== 5"
          class="mt-20 mb-20 text-60 fw-700 color-stress text-center pt-20 pb-20" type="number" placeholder="输入支付金额"
          style="border-bottom: 2rpx solid rgba(151,151,151,0.3);" placeholder-class="fw-400" />
      </view>
      <view class="mt-60">
        <label class="text-26">请选择支付方式: </label>
        <view class="mt-10">
          <view @click="checkedItem(index)" class="flex-row mt-30 b-rounded-16 p-24 bg-[rgba(211,211,211,0.1)]" :style="index === options.current
            ? { border: `1px solid #8777e1` } : { border: `1px solid transparent` }
            " v-for="(option, index) in options.list">
            <label class="flex-1 justify-center">
              <uv-icon size="40" :name="option.icon" />
              <text class="ml-10 text-22">
                {{
                  (option.pay_type === 7 ? card?.card_no ? `银行卡 ${card?.card_no}` : option.name : option.name) || "-"
                }}
              </text>
            </label>
            <view class="w-24">
              <uv-icon v-if="option.pay_type === 7" size="24" color="#fff" name="arrow-right" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <button @click="beforePay" hover-class="op-[0.6]"
      class="flex-row items-center justify-center bg-primary fw-700 b-rounded-16"
      style="margin: 88rpx 30rpx; line-height: 3">
      <uv-icon size="40" name="/static/img/icon-YUAN.svg" />
      <text class="ml-12 color-base text-32">立即支付</text>
    </button>

    <uv-popup :ref="(e: any) => (showPopup.captcha = e)" mode="center" closeable :close-on-click-overlay="false"
      close-icon-color="#fff">
      <view class="b-rounded-20 bg-section p-30" style="width: 600rpx">
        <label class="text-36 fw-700">验证手机号</label>
        <text class="mt-30">发送短信验证码至手机</text>
        <view class="mt-30 flex-row items-center bg-4 b-rounded-20">
          <input v-model="formData.captcha.value" class="flex-1 pl-30 pr-30 h-88" placeholder="请输入验证码" type="number"
            maxlength="6" placeholder-class="color-placeholder" />
          <button @click="getCaptcha" :disabled="formData.captcha.disabled" hover-class="op-[0.6]"
            class="bg-primary text-28 color-base fw-600 b-rounded-16 lh-60">
            {{ formData.captcha.text }}
          </button>
        </view>
        <button @click="submit" hover-class="op-[0.6]" style="line-height: 88rpx"
          class="flex-row bg-primary b-rounded-16 justify-center items-center m-30">
          <text class="ml-8 text-32 color-base fw-600">确认</text>
        </button>
      </view>
    </uv-popup>

    <pay-password v-model="formData.password.value" @finish="pay" ref="passwordPopup" />

  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import { debounce, isAbsoluteURL, parseJSON, sleep, uniNavigator } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme, card } = useMapState(["theme", "card"]);
const { $bridge } = getApp().globalData || {};
const goodsInfo = ref<AnyObject>({});
const apply_id = ref("");

const showPopup = reactive({
  captcha: {} as AnyObject,
});
const passwordPopup = ref({} as AnyObject);

const options = reactive({
  current: 0,
  list: [] as any[],
});
const formData = reactive({
  captcha: {
    text: "验证码",
    errorMessage: "验证码输入有误",
    disabled: false,
    count: 60,
    timer: null as any,
    value: "",
    field: "code",
    rule: /^[0-9]{4,6}$/,
  },
  password: {
    value: "",
  },
});

onLoad(async () => {
  const goodsData: AnyObject = await uni.getStorage({
    key: "payInfo",
  });
  goodsInfo.value = goodsData;

  uni.request({
    url: "/paySelect",
    success({ data }: any) {
      options.list =
        goodsData.order_type === 5
          ? data.filter((item: any) => item.pay_type !== 3)
          : data;
    },
  });
});

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey][e ? "open" : "close"]();
};

const getCaptcha = () => {
  countDown();
  uni.request({
    url: "/sendBankSms",
    data: {
      pay_id: apply_id.value,
    }
  });
};
const countDown = () => {
  const { captcha } = formData;
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  };
  return (captcha.timer = setInterval(intervalTask(), 1000));
};

const afterPay = () => {
  switch (+goodsInfo.value.order_type) {
    case 3:
      uniNavigator({ type: "navigateBack" });
      break;
    default:
      uniNavigator({ url: "/pages/client/mall/orders", type: "redirectTo" });
      break;
  }
}

const beforePay = debounce(() => {
  if (options.list[options.current].pay_type === 8) {
    passwordPopup.value.change(true);
    return;
  }
  pay();
});

const pay = () => {
  if (options.list[options.current].pay_type === 8) {
    passwordPopup.value.change(false);
  }

  uni.showToast({ icon: "loading", mask: true });
  uni.request({
    url: "/payment",
    data: {
      channel: options.list[options.current].pay_type,
      order_type: goodsInfo.value.order_type,
      order_id: goodsInfo.value.order_id || goodsInfo.value.amount,
      card_id: card.value?.id,
      pay_pass: formData.password.value
    },
    success({ data, order_sn }: any) {
      if (options.list[options.current].pay_type == 7) {
        apply_id.value = data.url;
        countDown();
        changePopup(true, "captcha");
        return
      }
      uni.hideToast();
      if (isAbsoluteURL(data.url?.toString())) {
        uniNavigator({ url: data.url });
        function checkResult() {
          uni.showModal({
            title: "支付中",
            content: "是否已完成支付？",
            confirmText: "支付完成",
            async success({ cancel }) {
              if (cancel) return;
              return afterPay();
            },
            complete: () => uni.offAppHide(checkResult),
          });
        }
        uni.onAppHide(checkResult);
        return;
      }
      if (+options.list[options.current].pay_type === 1) {
        $bridge.call?.("zfbApi.aliPay", { orderInfo: data }, async (result: any) => {
          if (Number(parseJSON(result)?.status) === 9000) {
            uni.showToast({ title: "支付成功", duration: 1200, mask: true });
            await sleep(1.2);
            return afterPay();
          }
          uni.showToast({ title: "支付失败", duration: 1200, icon: "error" });
          await sleep(1.2);
          uniNavigator({
            url: goodsInfo.value.url || "/pages/client/mall/orders?type=1",
            type: "reLaunch"
          });
        });
      }
      if (+options.list[options.current].pay_type === 2) {
        $bridge.call?.("wxpayApi.wxpay", { orderInfo: data }, async (result: any) => {
          if (Number(parseJSON(result)?.status) === 9000) {
            uni.showToast({ title: "支付成功", duration: 1200, mask: true });
            await sleep(1.2);
            return afterPay();
          }
          uni.showToast({ title: "支付失败", duration: 1200, icon: "error" });
          await sleep(1.2);
          uniNavigator({
            url: goodsInfo.value.url || "/pages/client/mall/orders?type=1",
            type: "reLaunch"
          });
        });
      }
    },
  });
};

const checkedItem = (index: number) => {
  options.current = index;
  if (options.list[index].pay_type === 7) {
    uniNavigator({ url: "/pages/client/mall/cards?enabled_select_card=1" });
  }
}

const submit = () => {
  uni.request({
    url: "/confirmBankPay",
    data: {
      sms_code: formData.captcha.value,
      pay_id: apply_id.value,
    },
    success: ({ data }: any) => {
      uniNavigator({ url: goodsInfo.value.url || "/pages/client/mall/orders", type: "reLaunch" });
    },
  });
};

</script>
<style lang="scss" scoped>
// scss
</style>
